/*
 Developer: John Archer (john.archer.jpa@gmail.com)
 
 This file is part of VTBuilder.

 VTBuilder is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License.

 VTBuilder is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with VTBuilder.  If not, see <http://www.gnu.org/licenses/>.
 */
package core.tasks;

import core.para.Para;
import core.rb.IB;
import core.tasks.pack.DNPack;
import gui.processor.Processor;
import gui.utils.ProgBar;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class DeNovo {

    protected ArrayList<IB> partitions;
    private boolean showProg;

    //this is the main one that will use many groups
    public DeNovo(ArrayList<IB> bns, boolean showProg) {
        this.partitions = bns;
        Collections.sort(partitions, new IB());
        this.showProg = showProg;
    }

    public ArrayList<String> deNovo(Processor p) throws Exception {
        int reqTrds = Para.TRDS;
        int done = 0;
        int noOfPacks = partitions.size();
        DecimalFormat df = null;
        if(showProg){
            if(Para.GUI){p.dPrgA(ProgBar.START, noOfPacks);}
            else{df = new DecimalFormat("##.##");}
        }
        CountDownLatch cdl = new CountDownLatch(noOfPacks);
        ArrayList <DNPack> packs = new <DNPack> ArrayList();
        ExecutorService executorService = Executors.newFixedThreadPool(reqTrds);
        do{
            DNPack pac = new DNPack(cdl, partitions.get(done).reads, null);
            packs.add(pac);
            executorService.execute(pac);
            done++;
            if(showProg){
                if(Para.GUI){p.dPrgA(ProgBar.UPDATE, done);}
                else{System.out.print("\r de novo: "+ df.format(((double)done/noOfPacks) * 100) + "%");}
            }
        }while(done < noOfPacks);
        cdl.await();
        executorService.shutdown();
        ArrayList<String> comb = new ArrayList<String>();
        for (DNPack pac : packs) {
            if(pac.pOut!=null){
                comb.addAll(pac.pOut);
            }
        }
        if(showProg){
            if(Para.GUI){
                p.dPrgA(ProgBar.END, 0);
            }
            else{System.out.println("\n");}
        }
        return comb;
    }
}